from flask import Blueprint, jsonify, request
import json
from db import db1

bp_day01 = Blueprint('day01', __name__)


@bp_day01.route('/yewu', methods=['POST', 'GET'])
def yewu():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into yewu values (%d,"%s","%s")""" % (0, data['name'], "")
        db1.update(sql)
        return jsonify({'code': 200})

    elif request.method == 'GET':
        sql = """select * from yewu"""
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_day01.route('/update', methods=['POST', 'GET'])
def update():
    if request.method == 'POST':
        data = get_data()
        print(data)
        sql = '''update yewu set parms = '%s' where id = %d ''' % (data['parms'], int(data['id']))
        print(sql)
        db1.update(sql)
        return jsonify({"code": 200})
    else:
        id = request.args.get('id')
        sql = '''select * from yewu where id = %d ''' % (int(id))
        res = db1.findone(sql)
        print(res)
        return jsonify({'code': 200, 'list': res})


@bp_day01.route('/apply', methods=['POST'])
def apply():
    data = get_data()
    print(data)
    sql = '''insert into apply values (0,%d,%d,"%s")''' % (int(data['userid']), int(data['wid']), data['params'])
    db1.update(sql)
    return jsonify({'code': 200})
